sugarfreeServices.constant('AUTH_EVENTS', {
  loginSuccess: 'auth-login-success',
  loginFailed: 'auth-login-failed',
  logoutSuccess: 'auth-logout-success',
  sessionTimeout: 'auth-session-timeout',
  notAuthenticated: 'auth-not-authenticated',
  notAuthorized: 'auth-not-authorized'
});

sugarfreeServices.constant('USER_ROLES', {
  all: '*',
  admin: 'admin',
  editor: 'editor',
  guest: 'guest'
});

sugarfreeServices.factory( 'Utils', ['$log','$filter','$location','$timeout', function($log,$filter,$location,$timeout) {
    var log={debug:false};
	var service = {
      isUndefinedOrNull: function(obj) {
        return !angular.isDefined(obj) || obj===null;
      },
      setParclose:function(isSet){
    	  if(isSet){
    		  $("#parclose").addClass("parclose");
    	  }else{
    		  $("#parclose").removeClass("parclose");
    	  }
      },
      setTopParclose:function(isSet){
    	  if(isSet){
    		  $("#parclose_top").addClass("parclose_top");
    	  }else{
    		  $("#parclose_top").removeClass("parclose_top");
    	  }
      },
      setProcessParclose:function(isSet){
    	  if(isSet){
    		  $("#parclose_process").addClass("sf_process");
    	  }else{
    		  $("#parclose_process").removeClass("sf_process");
    	  }
      },
      focusBox:function(){
    	  /*$(".side_form").addClass("focus_box");
    	  $timeout(function () {
    		  $(".side_form").removeClass("focus_box");
    	  }, 200);*/
      },
      focusTopBox:function(){
    	  /*$("#operation_box").addClass("focus_box");
    	  $timeout(function () {
    		  $("#operation_box").removeClass("focus_box");
    	  }, 200);*/
      },
      //now only equals base data type
	  equals:equals,
	  //now only equals base data type
	  existsElement:existsElement
  };
  
  //undetermined delete
  function equals(obj,targetObj,rejects){
		rejects = rejects || [];
		var ret = true;
//		angular.forEach(obj,function(value,key){
//			if(key.indexOf('$$') == -1 && rejects && !existsElement(rejects,key)){
//				if(typeof targetObj[key] === "object" && value === "object"){
//					return equals(value,targetObj[key],rejects);
//				}else{
//					if(targetObj[key] !== value){
//						$log.error("target "+ key +" : " + targetObj[key],"  &  ","SOURCE "+ key +" : " + value);
//						$log.error("target "+ key +" : ",targetObj[key]);
//						$log.error("SOURCE "+ key +" : ",value);
//						result = false;
//					}
//				}
//			}
//		});
		
		//应用浅比较
		for(var key in obj){
			if(key.indexOf('$$') === -1 && rejects && !existsElement(rejects,key)){
				if(log.debug){
					$log.info(typeof targetObj[key]);
				}
				if(typeof targetObj[key] === "object" && typeof obj[key] === "object"){
					var found = $filter('filter') ([obj[key]],targetObj[key], true);
					
					//delay
//					var o = obj[key];
//					var t = targetObj[key];
//					if(key=="contract"){
//						for(k in o){
//							console.log("k",k);
//							if(o[k] != t[k]){
//								$log.error(key);
//							}
//						}
//					}
					
					if(found.length === 0){
						$log.error(key);
						$log.error(targetObj[key]);
						$log.error(obj[key]);
						ret = false;
					}
				}else{
					if(targetObj[key] !== obj[key]){
						if(log.debug){
							$log.error("target "+ key +" : " + targetObj[key],"  &  ","SOURCE "+ key +" : " + obj[key]);
							$log.error("target "+ key +" : ",targetObj[key]);
							$log.error("SOURCE "+ key +" : ",obj[key]);
						}
						ret = false;
					}
				}
			}
		}

		return ret;
	}

	function existsElement(values,element){
		var ret = false;
		angular.forEach(values,function(value){
			if(value === element){
				ret = true;
			}
		});
		return ret;
	}
  

  return service;
}]);


sugarfreeServices.factory('AuthService',['$http','$cookies','$rootScope', 'Session',function ($http, $cookies, $rootScope, Session) {
  var authService = {};
 
  authService.login = function (credentials) {
    var _queryLogin = "login";
    var _dataStr = "?account=" + credentials.account +
                   "&password=" + credentials.password + 
                   "&captcha=" + credentials.captcha; 
    var _urlLogin = _queryLogin + _dataStr;
    var _urlLogin2 = _queryLogin;
    console.log("authService.login", credentials, _urlLogin);
    return $http
      // .post(_urlLogin2, _dataStr)
      .get(_urlLogin)
      .then(function (res) {
        
        $rootScope.cookieValue = $cookies.get('JSESSIONID');
        $rootScope.currentUser = res.data.account;
        console.log('authService success', res, $rootScope.cookieValue, $rootScope.currentUser);

        // this is more ideal response
        // Session.create(res.data.id, res.data.user.id, res.data.user.role);

        // temp solution based on return data
        Session.create(res.data.account, res.data.id, 'admin');

        return res.data;
      });
  };
 
  authService.isAuthenticated = function () {
    return !!Session.userId;
  };
 
  authService.isAuthorized = function (authorizedRoles) {
    if (!angular.isArray(authorizedRoles)) {
      authorizedRoles = [authorizedRoles];
    }
    return (authService.isAuthenticated() &&
      authorizedRoles.indexOf(Session.userRole) !== -1);
  };
 
  return authService;
}]);


sugarfreeServices.factory('AuthInterceptor',['$rootScope','$q','AUTH_EVENTS',function ($rootScope, $q, AUTH_EVENTS) {
  return {
    responseError: function (response) { 
      $rootScope.$broadcast({
        401: AUTH_EVENTS.notAuthenticated,
        403: AUTH_EVENTS.notAuthorized,
        419: AUTH_EVENTS.sessionTimeout,
        440: AUTH_EVENTS.sessionTimeout
      }[response.status], response);
      console.log('AuthInterceptor:', response.status);
      return $q.reject(response);
    }
  };
}]);


sugarfreeServices.service('Session',[function () {
  this.create = function (sessionId, userId, userRole) {
    this.id = sessionId;
    this.userId = userId;
    this.userRole = userRole;
  };
  this.destroy = function () {
    this.id = null;
    this.userId = null;
    this.userRole = null;
  };
}]);





sugarfreeServices.constant('TIME_GROUP', {
	  am:{
		title:'上午',
		startHour:0,
		endHour:12
	  },
	  cm:{
		title:'中午',  
		startHour:12,
		endHour:14  
	  },
	  pm:{
		title:'下午',    
		startHour:12,
		endHour:24  
		  
	  },
	  nm:{
		title:'晚上',
		startHour:18,
	    endHour:21   
	  },
	  array:['am','pm']
	  //array:['am','cm','pm','nm']
	});


sugarfreeServices.constant('ClassTypes', {
	  class_diy:{
		value:1,
		name:'自由课',
		shortName:'自'
	  },
	  class_group:{
		  value:2,
		  name:'团体课',
		  shortName:'团'
	  },
	  class_private:{
		  value:3,
		  name:'私教课',
		  shortName:'私'
	  },
	  array: [
		      {"value":1,"name":"自由课","shortName":"自"},
		      {"value":2,"name":"团体课","shortName":"团"},
		      {"value":3,"name":"私教课","shortName":"自"}
		    ]
});


sugarfreeServices.constant('MESSAGE', {
	  leesonTpl:{
		title:'上午'
	  }
	});

	
sugarfreeServices.service('TimeService',['TIME_GROUP',function(TIME_GROUP){
	var service = {};
	service.getTimeGroupRange = function(group){
		
		return TIME_GROUP[group];
	};
	
	service.parse = function(date,pattern){
		var _year = ""+(date.getFullYear());
		var _month = ""+(date.getMonth() + 1);
		var _date = ""+date.getDate();
		var _hour = ""+date.getHours();
		var _minute = ""+date.getMinutes();
		var _second = ""+date.getSeconds();
		var _fullMonth = _month.length > 1?_month:"0"+_month;
		var _fullDate = _date.length > 1?_date:"0"+_date;
		var _fullHour = _hour.length > 1?_hour:"0"+_hour;
		var _fullMinute = _minute.length>1?_minute:"0"+_minute;
		var _fullSecond = _second.length>1?_second:"0"+_second;
		if("yyyyMMddHHmm" === pattern){
			return _year + _fullMonth + _fullDate + _fullHour + _fullMinute;
		}else if("yyyyMMdd" === pattern){
			return _year + _fullMonth + _fullDate;
		}else if("yyyy.MM.dd" === pattern){
			return _year +"."+ _fullMonth +"."+ _fullDate;
		}else if("HH:mm" === pattern){
			return _fullHour + ":" + _fullMinute;
		}else{
			return _year + _fullMonth + _fullDate + _fullHour + _fullMinute + _fullSecond;
		}
	};
	
	service.format = function(date_str){
		var date = new Date('201509301421');
		return date_str;
	};
	
	//yyyyMMddHHmm
	service.patten = function(date_str,patten){
		if(!date_str){
			return "";
		}
		return date_str.substr(0,4) + "-" +
		       date_str.substr(4,2) + "-" +
			   date_str.substr(6,2) + " " +
			   date_str.substr(8,2) + ":" +
			   date_str.substr(10,2);
	};
	
	service.getDateByWeekAndDayOfWeek = function(week,dayOfWeek){
		var now = new Date();
		var nowOfWeek = now.getDay();
		if(nowOfWeek===0){
			nowOfWeek = 7;
		}
		var subDayOfWeek = dayOfWeek - nowOfWeek + week * 7;
		var rstDateTime = now.getTime() + 24*60*60*1000*subDayOfWeek;
		now.setTime(rstDateTime)
//		console.info('rstDate',subDayOfWeek);
//		console.info('rstDate',now);
		return service.parse(now,'yyyy.MM.dd');
	};
	return service;
}]);



sugarfreeServices.factory('DictionarySerivce',['$http','HttpService',function($http,httpService){
	var dicService = {
		getGym:getGym,
		//get with gym sign a contract coachs
		getCoachs:getCoachs,
		
		getContract:getContract,
		
		getDayOfWeeks:getDayOfWeeks,
			
		getLessonStatus:getLessonStatus,
		
		getClassTypes:getClassTypes,
		
		getSports:getSports,
		
		getPrices:getPrices,
		
		queryCourses:queryCourses,
		
		queryDevice:queryDevice,
		
		getShengShi:getShengShi,
		
		getShiQuXian:getShiQuXian,
		
		getShangQuan:getShangQuan	
	};
	return dicService;
	
	///////////
	
	function getCoachs(status){
		status = status || 2;
		var queryCoachesUrl = "filter/coaches?status=" + status;
		return $http.get(queryCoachesUrl);
	}
	
	function getContract(status){
		status = status || 2;
		var queryContractsUrl = "contract/query?status=" + status;
		return $http.get(queryContractsUrl);
	}
	
	function getPrices(classTypeV){
	      var _queryPrices = "course/price/query?classType="+ classTypeV;
	      return $http.get(_queryPrices);
	}
	
	function getSports(classType){
		var querySportsUrl = "filter/sports?classType=" + classType;
		return $http.get(querySportsUrl);
	}
	
	function getClassTypes(){
		return{
				  class_diy:{
					value:1,
					name:'自由课',
					shortName:'自'
				  },
				  class_group:{
					  value:2,
					  name:'团体课',
					  shortName:'团'
				  },
				  class_private:{
					  value:3,
					  name:'私教课',
					  shortName:'私'
				  },
				  array: [
					      {"value":1,"name":"自由课","shortName":"自"},
					      {"value":2,"name":"团体课","shortName":"团"},
					      {"value":3,"name":"私教课","shortName":"自"}
					    ]
			};
	}
	
	function getDayOfWeeks(){
		return [
                  {"value": 2, "name": "星期一"},
                  {"value": 3, "name": "星期二"},
                  {"value": 4, "name": "星期三"},
                  {"value": 5, "name": "星期四"},
                  {"value": 6, "name": "星期五"},
                  {"value": 7, "name": "星期六"},
                  {"value": 1, "name": "星期日"}
               ];
	}
	
	function getLessonStatus(){
		return {
					open:{
						value:0,
						name:'未开始'
					},
					proceed:{
						value:1,
						name:'进行中'
					},
					outdated:{
						value:2,
						name:'已结束'
					},
					closed:{
						value:3,
						name:'已关课'
					},
					later:{
						value:4,
						name:'待上课'
					}
			   };
	}
	
	function queryCourses(classTypeV){
	   return $http.get("course/query?classType=" + classTypeV);
	}
	
	function queryDevice(){
		return  $http.get("filter/devices");
	}
	
	function getShengShi(){
		return $http.get("filter/shengShi");
	} 
	function getShiQuXian(shengshi){
		return	$http({
		          method: 'POST',
		          url: "filter/shiQuXian",
		          data: "shengShi=" + shengshi,
		          headers: {'Content-Type': 'application/x-www-form-urlencoded'}
	      		});
	} 
	function getShangQuan(shengshi,shiquxian){
		return	$http({
	          method: 'POST',
	          url: "filter/shangQuan",
	          data: "shengShi=" + shengshi + "&shiQuXian=" + shiquxian,
	          headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    		});
	}
	
	function getGym(){
		return httpService.get("profile/get");
	}
	
}]);